package com.project.api.sale.controller;

import com.project.api.common.ApiResponse;
import com.project.api.common.Http;
import com.project.api.common.wxpay.WXPayConstants;
import com.project.api.common.wxpay.WXPayUtil;
import com.project.api.sale.dao.OrderDao;
import com.project.api.sale.common.Weixin;
import com.project.api.sale.service.AdminService;
import com.project.api.sale.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONArray;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Controller
public class WeixinBaseController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private AdminService adminService;
    private Logger logger = LoggerFactory.getLogger(getClass());
    @ResponseBody
    @RequestMapping("/menu")
    public String Menu(HttpServletRequest request) throws JSONException {
        HttpSession session=request.getSession();
        Object access_token=session.getAttribute("access_token");
        String token=null;
        if(access_token==null){
            return ApiResponse.Fail("请从微信登录");
        }
        token=(String)access_token;
        String url="https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+token;
//        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        JSONObject pg=new JSONObject();
        pg.put("type","view");
        pg.put("name","立即团购");
        pg.put("url","https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxacb1a566d582d66a&redirect_uri=http%3a%2f%2fapi.wensry.com%2fmallIndex&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
        JSONArray button=new JSONArray();
        button.put(pg);
        JSONObject parentObj=new JSONObject();
        parentObj.put("button",button);
        String jsonStr= parentObj.toString();
//        params.add("body",jsonStr);
        String result= Http.pPost(url,jsonStr);
        return result;
    }
    @RequestMapping("/payback")
    @ResponseBody
    public String Payback(HttpServletRequest request,@RequestBody String WxMsg){
        logger.warn(WxMsg);
        try {
            Map<String,String> msg= WXPayUtil.xmlToMap(WxMsg);
            String return_code=msg.get("return_code");
            String number=msg.get("out_trade_no");//商户订单编号
            String total=msg.get("total_fee");//总金额
            int total_fee=Integer.parseInt(total);
            if(return_code.equalsIgnoreCase("SUCCESS")){
                String sign=msg.get("sign");
                Iterator<String> iterator = msg.keySet().iterator();
                while (iterator.hasNext()) {
                    String key = iterator.next();
                    if(key.equalsIgnoreCase("sign")){
                        iterator.remove();
                    }
                }
                String signStr=WXPayUtil.generateSignature(msg,Weixin.KEY, WXPayConstants.SignType.HMACSHA256);
                if(signStr.equals(sign)){
                    logger.warn("订单编码为:"+number);
                    OrderDao orderDao=orderService.getOrderByNumber(number);
                    double to=orderDao.getTotal();
                    if(to*100==total_fee){
                        int count=orderService.updateOrder(number,1);
                    }
                    String openid=msg.get("openid");
                    double money=Double.parseDouble(total)/100;
                    BigDecimal b=new BigDecimal(money);
                    money=b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
//                    String total_moeny=String.valueOf(money);
                    System.out.println(money);
                    String productName=msg.get("attach");
                    String remark="";
                    Http.sendOrderPayMsg(openid,"我们已收到您的货款，开始为您打包商品，请耐心等候",money,productName,remark);
                    List list=adminService.getCustomerService();
                    for (int i=0;i<list.size();i++){
                        Map map=(Map)list.get(i);
                        String oid=(String) map.get("openid");
                        Http.sendOrderPayMsg(oid,"有客户下单啦！",money,productName,remark);
                    }
                    Map<String,String> response=new HashMap<String, String>();
                    response.put("return_code","SUCCESS");
                    response.put("return_msg","OK");
                    return WXPayUtil.mapToXml(response);
                }else{
                    logger.error("支付验证不通过:"+signStr);
                }
            }else{
                logger.error(WxMsg);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return WxMsg;
    }
}
